<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/sj-request'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ROLES } from '@/utils/permission'
import { usetikuUserStore } from  '@/stores/sj-user'

const router = useRouter()
const userStore = usetikuUserStore()

// 获取用户信息
const userInfo = computed(() => userStore.userInfo)

// 学科列表数据
const subjectList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)

// 新增学科对话框显示状态
const dialogVisible = ref(false)
// 是否为编辑模式
const isEdit = ref(false)
// 表单数据
const subjectForm = reactive({
  id: null,
  name: ''
})
// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入学科名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}
// 表单引用
const formRef = ref()

// 过滤后的学科列表
const filteredSubjects = computed(() => {
  // 首先按关键词过滤
  let filtered = subjectList.value
  if (searchKeyword.value) {
    filtered = filtered.filter(subject => 
      subject.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  // 然后根据用户角色和学科权限过滤
  if (userInfo.value.roleName === ROLES.ADMIN) {
    // 管理员可以看到所有学科
    return filtered
  } else if (userInfo.value.roleName === ROLES.SUBJECT_LEADER || userInfo.value.roleName === ROLES.TEACHER) {
  // 学科组长和教师只能看到自己所属的学科
  return filtered.filter(subject => userInfo.value.subjects.some(s => s.name === subject.name))
}
  
  return []
})

// 获取所有学科
const fetchSubjects = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/subject/list',
      method: 'get'
    })
    subjectList.value = res.data || []
  } catch (error) {
    console.error('获取学科列表失败:', error)
    ElMessage.error('获取学科列表失败')
  } finally {
    loading.value = false
  }
}

// 打开新增学科对话框
const openAddDialog = () => {
  dialogVisible.value = true
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  isEdit.value = false
  subjectForm.id = null
  subjectForm.name = ''
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const res = await request({
          url: isEdit.value ? `/subject/${subjectForm.id}` : '/subject',
          method: isEdit.value ? 'put' : 'post',
          data: subjectForm
        })
        
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '编辑学科成功' : '添加学科成功')
          dialogVisible.value = false
          fetchSubjects() // 刷新列表
        } else {
          ElMessage.error(res.message || (isEdit.value ? '编辑学科失败' : '添加学科失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '编辑学科失败:' : '添加学科失败:', error)
        ElMessage.error(isEdit.value ? '编辑学科失败' : '添加学科失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 组件挂载时获取学科列表
onMounted(() => {
  fetchSubjects()
})

const handleDeleteSubject = async (subject) => {
  try {
    await ElMessageBox.confirm('确定要删除该学科吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request({
      url: `/subject/${subject.id}`,
      method: 'delete'
    })

    if (res.code === 200) {
      ElMessage.success('删除学科成功')
      fetchSubjects() // 刷新列表
    } else {
      ElMessage.error(res.message || '删除学科失败')
    }
  } catch (error) {
    console.error('删除学科失败:', error)
    ElMessage.error('删除学科失败')
  }
}

const handleEditSubject = (subject) => {
  isEdit.value = true
  dialogVisible.value = true
  subjectForm.id = subject.id
  subjectForm.name = subject.name
}
</script>

<template>
  <div class="subject-container">
    <!-- 搜索框和操作按钮 -->
    <div class="search-container">
      <div class="left-container">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入学科名称搜索"
          clearable
          prefix-icon="Search"
          class="search-input"
        />
      </div>
      <div class="right-container">
        <el-button v-if="userInfo.roleName === ROLES.ADMIN" type="primary" @click="openAddDialog">新增学科</el-button>
      </div>
    </div>
    
    <!-- 学科卡片列表 -->
    <el-row :gutter="20" class="subject-list">
      <el-col 
        v-for="subject in filteredSubjects" 
        :key="subject.id" 
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="6" 
        :xl="4"
        class="subject-item"
      >
        <el-card 
          :body-style="{ padding: '0px' }" 
          shadow="hover" 
          class="subject-card"
        >
          <div class="subject-image" @click="router.push(`/home/subject-detail/${subject.id}`)">
            <!-- 使用学科首字母作为图标 -->
            <div class="subject-icon">
              {{ subject.name.charAt(0).toUpperCase() }}
            </div>
          </div>
          <div class="subject-info">
            <span class="subject-name">{{ subject.name }}</span>
            <div class="subject-actions">
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click="handleEditSubject(subject)" 
                :disabled="userInfo.roleName === ROLES.TEACHER"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                v-if="userInfo.roleName === ROLES.ADMIN" 
                type="danger" 
                size="small" 
                text 
                @click="handleDeleteSubject(subject)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 无数据时显示提示 -->
      <el-empty v-if="filteredSubjects.length === 0" description="暂无学科数据" />
    </el-row>
    
    <!-- 新增学科对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑学科' : '新增学科'"
      width="30%"
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="subjectForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="学科名称" prop="name">
          <el-input v-model="subjectForm.name" placeholder="请输入学科名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.subject-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.left-container {
  flex: 1;
}

.right-container {
  margin-left: 20px;
}

.subject-list {
  margin-top: 20px;
}

.subject-item {
  margin-bottom: 20px;
}

.subject-card {
  transition: all 0.3s;
  cursor: pointer;
}

.subject-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.subject-image {
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.subject-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36px;
  font-weight: bold;
}

.subject-info {
  padding: 14px;
  text-align: center;
}

.subject-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}
</style>